<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="default"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="deployTime">
        <el-date-picker
          clearable
          size="default"
          v-model="queryParams.deployTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="default" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          size="default"
          @click="handleAdd"
          v-hasPermi="['system:deployment:add']"
        >新增流程</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="IconDelete"
          size="default"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['system:deployment:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="流程编号" align="center" prop="procInsId" width="200" :show-overflow-tooltip="true"/>
      <el-table-column label="流程名称" align="center" prop="procDefName" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="流程类别" align="center" prop="category" width="100">
        <template #default="scope">
          <dict-tag
            v-if="dict && dict.sys_process_category && Array.isArray(dict.sys_process_category.value)"
            :options="dict.sys_process_category.value"
            :value="scope.row.category"/>
          <span v-else-if="scope.row.category">{{ scope.row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程版本" align="center" width="80">
        <template #default="scope">
          <el-tag size="small" v-if="scope.row.procDefVersion">v{{ scope.row.procDefVersion }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="流程状态" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.finishTime === null || scope.row.finishTime === undefined" size="small">进行中</el-tag>
          <el-tag type="success" v-if="scope.row.finishTime !== null && scope.row.finishTime !== undefined" size="small">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="耗时" align="center" prop="duration" width="180"/>
      <el-table-column label="当前节点" align="center" prop="taskName" :show-overflow-tooltip="true"/>
      <el-table-column label="办理人" align="center">
        <template #default="scope">
          <label v-if="scope.row.assigneeName">{{scope.row.assigneeName}} <el-tag type="info" size="small">{{scope.row.assigneeDeptName}}</el-tag></label>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button :icon="View" @click="handleFlowRecord(scope.row)" link size="small">详情</el-button>
          <el-button
            @click="handleStop(scope.row)"
            link
            size="small"
            v-if="scope.row.finishTime === null || scope.row.finishTime === undefined"
           >取消申请</el-button>
          <el-button
            @click="handleDelete(scope.row)"
            link
            size="small"
            v-hasPermi="['system:deployment:remove']"
           >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增流程 -->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-form :model="queryProcessParams" ref="queryProcessFormRef" :inline="true" label-width="68px">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryProcessParams.name"
            placeholder="请输入名称"
            clearable
            size="default"
            @keyup.enter="handleProcessQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="handleProcessQuery">搜索</el-button>
          <el-button :icon="Refresh" size="default" @click="resetProcessQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="processLoading" :data="definitionList" @row-click="handleRowClickDefinition" height="380" border>
        <el-table-column label="流程名称" align="center" prop="name" />
        <el-table-column label="流程版本" align="center" width="80">
          <template #default="scope">
            <el-tag size="default" >v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="流程分类" align="center" prop="category">
            <template #default="scope">
                <dict-tag
                    v-if="dict && dict.sys_process_category && Array.isArray(dict.sys_process_category.value)"
                    :options="dict.sys_process_category.value"
                    :value="scope.row.category"/>
                <span v-else-if="scope.row.category">{{ scope.row.category }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="default"
              link
              @click="handleStartProcess(scope.row)"
              v-hasPermi="['flowable:process:start']" 
            >发起流程</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="processTotal>0"
        :total="processTotal"
        v-model:page="queryProcessParams.pageNum"
        v-model:limit="queryProcessParams.pageSize"
        @pagination="listDefinitionFunc"
      />
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { myProcessList, stopProcess } from "@/api/flowable/process";
import { listDefinition } from "@/api/flowable/definition";
import { delDeployment } from "@/api/flowable/finished"; // Matching Vue2 import for delete
import { Search, Refresh, Plus, View, Delete as IconDelete } from '@element-plus/icons-vue';
import { ref, reactive, onMounted, getCurrentInstance, watchEffect } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { useDict } from '@/utils/dict';

const { proxy } = getCurrentInstance();
const router = useRouter();

const dict = useDict('sys_process_category');

// Log dict data for debugging
watchEffect(() => {
  if (dict && dict.sys_process_category) {
    // console.log('[myProcess/index.vue] dict.sys_process_category.value:', dict.sys_process_category.value);
    if (Array.isArray(dict.sys_process_category.value)) {
        dict.sys_process_category.value.forEach((item, index) => {
            if (item === undefined || item === null || item.value === undefined) {
                // console.error(`[myProcess/index.vue] Problematic item in sys_process_category.value at index ${index}:`, item);
            }
        });
    }
  } else {
    // console.log('[myProcess/index.vue] dict.sys_process_category is not yet available');
  }
});

const loading = ref(true);
const processLoading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const processTotal = ref(0);
const processList = ref([]);
const definitionList = ref([]);
const title = ref("");
const open = ref(false);

// For selection and batch delete, matching Vue2
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);


const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  deployTime: null,
});

const queryProcessParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  category: null,
});

const queryFormRef = ref(null);
const queryProcessFormRef = ref(null);

const getList = () => {
  loading.value = true;
  myProcessList(queryParams).then(response => {
    console.log("queryParams:", queryParams);
    console.log("response:", response);
    processList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const handleAdd = () => {
  open.value = true;
  title.value = "新增流程";
  listDefinitionFunc();
}

const listDefinitionFunc = () => {
  processLoading.value = true;
  listDefinition(queryProcessParams).then(response => {
    definitionList.value = response.data.records;
    processTotal.value = response.data.total;
    processLoading.value = false;
  }).catch(() => {
    processLoading.value = false;
  });
}

const handleProcessQuery = () => {
  queryProcessParams.pageNum = 1;
  listDefinitionFunc();
}

const resetProcessQuery = () => {
  queryProcessFormRef.value?.resetFields();
  handleProcessQuery();
}

const handleStartProcess = (rowDefinition) => {
  router.push({
    path: '/flowable/task/myProcess/send/index',
    query: {
      deployId: rowDefinition.deploymentId,
      procDefId: rowDefinition.id
    }
  });
  open.value = false;
}

const handleStop = (rowProcess) => {
  ElMessageBox.confirm('确认取消申请该流程吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    const params = { instanceId: rowProcess.procInsId };
    return stopProcess(params);
  }).then((res) => {
    ElMessage.success(res.msg || "取消申请成功");
    getList();
  }).catch(() => {});
}

const handleFlowRecord = (rowProcess) => {
  router.push({
    path: '/flowable/task/myProcess/detail/index',
    query: { // Matched with Vue2 query params
      procInsId: rowProcess.procInsId,
      deployId: rowProcess.deployId,
      taskId: rowProcess.taskId // Assuming taskId might be available on rowProcess
    }
  });
}

const handleDelete = (row) => {
  const deleteIds = row && row.procInsId ? [row.procInsId] : ids.value;
  if (deleteIds.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  ElMessageBox.confirm('是否确认删除流程实例编号为"' + deleteIds.join(',') + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    return delDeployment(deleteIds.join(','));
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.procInsId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

const handleRowClickDefinition = (rowDefinition) => {
}

const cancel = () => {
  open.value = false;
}

onMounted(() => {
  getList();
});

</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>

